package twitter 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	/**
	 * @author Nicolas Barradeau
	 * http://en.nicoptere.net
	 */
	public class Twitter extends EventDispatcher
	{
		
		static public var ns:Namespace;
		private var loader:URLLoader;
		private var req:URLRequest;
		private var vars:URLVariables;
		
		private var _resultsPerPage:String = "5";
		
		private var _entries:Vector.<TwitterEntry>;
		
		public function Twitter() 
		{
			
			ns = new Namespace( null, "http://www.w3.org/2005/Atom" );
			loader = new URLLoader();
			req = new URLRequest("http://search.twitter.com/search.atom");
			req.method = URLRequestMethod.GET;
			vars = new URLVariables();
			
			entries = new Vector.<TwitterEntry>();
			
		}
		
		public function request( keyword:String = "dimension", resultsPerPage:String = null ):void
		{
			
			if ( resultsPerPage != null )
			{
				this.resultsPerPage = resultsPerPage;
			}
			
			vars.q = keyword;
			vars.rpp = this.resultsPerPage;
			vars.page = 1;
			
			req.data = vars;
			
			if ( loader.hasEventListener(Event.COMPLETE ) )loader.removeEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.load(req);
			
		}	
		                           
		private function onComplete(evt:Event):void
		{
			
			loader.removeEventListener(Event.COMPLETE, onComplete);
			
		    var searchData:XML = new XML( loader.data );
			default xml namespace = ns;
			
		    for each( var twit:XML in searchData.descendants( 'entry' ) )
			{
				var entry:TwitterEntry = new TwitterEntry( twit );
				entries.push( entry );
		    }
			
			dispatchEvent( new Event( Event.COMPLETE ) );
			
		}
		
		public function get resultsPerPage():String { return _resultsPerPage; }
		
		public function set resultsPerPage(value:String):void 
		{
			_resultsPerPage = value;
		}
		
		
		public function get entries():Vector.<TwitterEntry> { return _entries; }
		
		public function set entries(value:Vector.<TwitterEntry>):void 
		{
			_entries = value;
		}
		
	}

}